#include "dir_img.h"
char perm[11];
void mode(struct stat *info)
{
    // 得到文件的类型
    switch(info->st_mode & S_IFMT) 
    {
        case S_IFBLK: perm[0]='b'; break; // 块设备
        case S_IFCHR: perm[0]='c'; break; // 字符设备
        case S_IFIFO: perm[0]='p'; break;
        case S_IFSOCK:perm[0]='s'; break;
        case S_IFDIR: perm[0]='d'; break;
        case S_IFREG: perm[0]='-'; break;
        case S_IFLNK: perm[0]='l'; break;
    }

    // 得到文件的权限
    char s[] = {'r', 'w', 'x'};
    for(int i=0; i<9; i++)
        perm[i+1] = (info->st_mode&(0400>>i)) ? s[i%3] : '-';
}
piclink read_imgdir(const char *target)
{
    struct stat info;
    stat(target,&info);
    mode(&info);
    int a=0;
    printf("获取目录相关信息没问题\n");
    piclink head=init_link();//初始化链表
    printf("初始化链表没问题\n");
    if(perm[0]!='d')
    {
        perror("请输入目录！");
        exit(0);
    }
    else
    {
        DIR *dp=opendir(target);
        if(dp==NULL)
        {
            perror("打开目录失败!");
            exit(0);
        }
        if(chdir(target)!=0)//判断是否成功改变目录
        {
            perror("改变目录失败！");
            exit(0);
        }
        struct dirent *ep;
        printf("成功切换目录\n");
        while(1)
        {
            ep=readdir(dp);
            
            if(ep==NULL)
            {
                printf("读完了！\n");
                break;
            }
            // printf("读取文件%s\n",ep->d_name);
            if (strstr(ep->d_name, ".jpg") != NULL || strstr(ep->d_name, ".jpeg") != NULL ||
                strstr(ep->d_name, ".bmp") != NULL || strstr(ep->d_name, ".png") != NULL)
            {
                struct img_info *imginfo=calloc(1,sizeof(struct img_info));
                strcpy(imginfo->name,ep->d_name);
                // printf("成功拷贝图片：%s\n",ep->d_name);
                head=pic_add_link(head,newnode(imginfo));
                // printf("%s存入链表成功\n",ep->d_name);
                a++;
            }
        }
        if(a==0)
        {
            printf("该目录下没有jpg、png、bmp格式的图片！\n");
            printf("请更换别的目录！\n");
            exit(0);
        }
    }
    printf("初始化图片链表完成\n");
    return head;
}